package com.cylise.compass;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener{
    ObjectAnimator animator1;
    ImageView imageView;
    TextView textView;
    float f;
    float currentValues;
    private SensorManager mSensorManager;
    private Sensor mMagneticSensor,mAccelerometerSensor;
    float[] accelerometerValues = new float[3];
    float[] magneticFieldValues = new float[3];
    protected final Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mMagneticSensor=mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        imageView = (ImageView) findViewById(R.id.imageViewCompass);
        textView= (TextView) findViewById(R.id.degrees);
        f=0;
        refreshDegrees();
        mHandler.postDelayed(mCompassUpdater,300);
    }

    private void refreshDegrees() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (this){
                    float[] values = new float[3];
                    float[] R = new float[9];
                    if (SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticFieldValues)){
                        SensorManager.getOrientation(R, values);

                        // 要经过一次数据格式的转换，转换为度
                        values[0] = (float) Math.toDegrees(values[0]);
                        currentValues=values[0]>=0?values[0]:360+values[0];
                    }

                }


            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this,mMagneticSensor,SensorManager.SENSOR_DELAY_NORMAL);
        mSensorManager.registerListener(this,mAccelerometerSensor,SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
            magneticFieldValues=event.values.clone();
        }
        if (event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD){
            accelerometerValues=event.values;
        }
        refreshDegrees();
       /*if (Math.abs(f-(0-event.values[0]))>=2){
            animator1=ObjectAnimator.ofFloat(imageView,"rotation",f,0-event.values[0]);
            animator1.setDuration(700);
            animator1.setInterpolator(new AccelerateInterpolator());
            animator1.start();
            Log.d("compass",event.values[0]+"    "+event.values[1]+"    "  +event.values[2]+"    "+Math.abs(f-event.values[0])+"   "+f);
            f=0-event.values[0];

        }*/
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    Runnable mCompassUpdater =  new Runnable() {
        @Override
        public void run() {
            if (Math.abs(f-currentValues)>2){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (Math.abs(f-currentValues)>180f) {
                            if (f>180f){
                                animator1=ObjectAnimator.ofFloat(imageView,"rotation",f,360f+currentValues);
                            } else {
                                animator1=ObjectAnimator.ofFloat(imageView,"rotation",f,currentValues-360f);
                            }
                        } else {
                            animator1=ObjectAnimator.ofFloat(imageView,"rotation",f,currentValues);
                        }
                        animator1.setDuration(300);
                        animator1.setInterpolator(new AccelerateInterpolator());
                        animator1.start();
                        Log.d("compass",currentValues+"    "+f);
                        f=currentValues;
                        textView.setText((int)(f>=0?360-f:Math.abs(f))+"°");
                    }
                });
            }
            mHandler.postDelayed(mCompassUpdater,300);
        }
    };
}
